﻿// 服务端，渲染生成环境 ================= 
/***
 * 
 * 视频通话生成token
 * 
 */
let express = require('express');
// websocket - express
let expressWs = require('express-ws');
let https = require('https')
// ejs模块
let ejs = require('ejs');
let path = require('path');
// 操作文件
let fs = require('fs');
const os = require('os');
// 接受表单文件
let app = express();
// 视频通话token获取
let { getToken } = require('./token.js')

// SSL
let options = {
    key: fs.readFileSync('./ssl/qiaonan.info.key'),
    cert: fs.readFileSync('./ssl/qiaonan.info_bundle.crt')
}

let server = https.createServer(options, app)
// 配置wss
let WSS = expressWs(app, server, {
    wsOptions: {
        options,//ssl
    }
});
server.listen(8126, () => {
    console.log('本机服务器地址：', 'https://localhost:8126', '或', `https://${getIpAddress()}:8126`)
})

/* 
 const wsOptions = options.wsOptions || {};
  wsOptions.server = server;
  const wsServer = new ws.Server(wsOptions);
*/
// 使用 req.body
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.engine('html', ejs.__express)
// 静态资源
app.use(express.static(path.join(__dirname, 'upload')))
app.use(express.static(path.join(__dirname, 'dist')))
app.use(express.static(path.join(__dirname, 'src')))
// 解决跨域
app.use((req, res, next) => {
    //设置请求头
    res.set({
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Max-Age': 1728000,
        'Access-Control-Allow-Origin': req.headers.origin || '*',
        'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type,user-id',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
        'Content-Type': 'application/json; charset=utf-8'
    })
    req.method === 'OPTIONS' ? res.status(204).end() : next()
})
app.get('/', (req, res) => {
    res.render('../dist/index.html');
})
// 获取视频第三方token
app.get('/get/token', (req, res) => {
    const {'user-id':userId} = req.headers || {};
    const {username} = req.query || {};
    const token = getToken({
        appID: 839080308,
        serverSecret: '95debb6a778719428e871144be56e06f',
        userId: userId,
        effectiveTimeInSeconds: 3600
    })
    res.send({
        flag: true,
        message: "获取成功",
        data: {
            token
        }
    })
})

/**
 * 获取当前机器的ip地址
 */
function getIpAddress() {
    var ifaces = os.networkInterfaces()
    for (var dev in ifaces) {
        let iface = ifaces[dev]
        for (let i = 0; i < iface.length; i++) {
            let { family, address, internal } = iface[i]
            if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
                return address
            }
        }
    }
}